// pages/individual/update/index.js
import request from '../../../utils/request'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    current: {
      name: '',
      university: '',
      uid: '',
      phone_number: ''
    },
    prev: {
      name: '',
      university: '',
      uid: '',
      phone_number: ''
    },
    openid: '',
    hide: true
  },

  fetchInputValue(e) {
    const { current, prev } = this.data
    const { key } = e.currentTarget.dataset
    const { value } = e.detail.detail
    current[key] = value
    if (current.name === prev.name &&
      current.uid === prev.uid &&
      current.phone_number === prev.phone_number &&
      current.university === prev.university) {
        // 如果信息内容没有更新，则隐藏确认按钮
        this.setData({ hide: true })
      }
    this.setData({ current, hide: false })
  },

  // 返回原来的信息
  resetForm() {
    const { current, prev } = this.data
    Object.assign(current, prev)
    this.setData({ current })
  },

  async useUpdate() {
    const { current } = this.data
    wx.showLoading({ title: '更新中···', mask: true })
    request.post('/user/update', { ...current }).then(result => {
      console.log('请求成功', result)
    }).catch(() => {
      console.log('请求出错')
    }).finally(() => {
      wx.hideLoading()
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const _this = this
    const { prev, current } = this.data
    const event = this.getOpenerEventChannel()
    event.on('deliverUserInfo', function ({ userInfo }) {
      const { name, uid, university, phone_number } = userInfo
      current.name = name
      current.uid = uid
      current.university = university
      current.phone_number = phone_number

      prev.name = name
      prev.uid = uid
      prev.university = university
      prev.phone_number = phone_number

      _this.setData({ current, prev, openid: app.globalData.userInfo.openid })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})